package org.misterhou.spring.boot.demo.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

@ClientEndpoint
@Component
@Slf4j
public class WebSocketClient {

    private Session session;

    private Session proxySession;

    public void setProxySession(Session session) {
        this.proxySession = session;
    }

    public WebSocketClient() {
        WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
        try {
            webSocketContainer.connectToServer(this, new URI("ws://124.222.224.186:8800"));
        } catch (DeploymentException | IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        log.info("已连接");
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("接收到的消息：{}", message);
        if (null != this.proxySession) {
            try {
                this.proxySession.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnClose
    public void onClose(Session session) {
        log.info("已断开");
    }

    public void sendMessage(String message) {
        if (null != this.session) {
            try {
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
